/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.core.http.impl;

import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lt.ntec.danblog.server.core.UserManager;
import lt.ntec.danblog.server.core.http.Flow;
import lt.ntec.danblog.server.core.http.NoValidUserException;
import lt.ntec.danblog.server.core.http.ServletRedirectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Tadas
 */
class SimpleFlow implements Flow {

    private static final Logger LOG = LoggerFactory.getLogger(SimpleFlow.class);
    @Inject
    private UserManager userManager;
    @Inject
    private HttpServletRequest request;
    @Inject
    private HttpServletResponse response;

    @Override
    public void requireValidUser() {
        if (!userManager.isAvailableValidUser()) {
            try {
                response.sendRedirect(userManager.getLoginUrl(
                        request.getRequestURI()));
                throw new NoValidUserException();
            } catch (IOException ex) {
                LOG.error("Could not redirect", ex);
            }
        }
    }

    @Override
    public void redirect(String url) {
        try {
            
            if(LOG.isDebugEnabled()) {
                LOG.debug("Redirecting to: " + url);
            }
            
            response.sendRedirect(url);
            throw new ServletRedirectException();
        } catch (IOException ex) {
            LOG.error("Could not redirect", ex);
        }
    }
}
